package com.wayne.blog.controller;

import com.wayne.blog.common.Ret;
import com.wayne.blog.dto.LoginDTO;
import com.wayne.blog.dto.RegisterDTO;
import com.wayne.blog.entity.User;
import com.wayne.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Lang
 * @since  2025/06/06
 *
 * 用户相关接口
 */
@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Ret<?> register(@RequestBody RegisterDTO registerDTO) {
        try {
            userService.register(registerDTO);
            return Ret.success();
        } catch (Exception e) {
            return Ret.error(e.getMessage());
        }
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Ret<?> login(@RequestBody LoginDTO loginDTO) {
        String token = userService.login(loginDTO.getUsername(), loginDTO.getPassword());
        if (token != null) {
            User user = userService.getByUsername(loginDTO.getUsername());
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("user", user);
            // 检查是否是管理员
            boolean isAdmin = user.getRoles() != null && user.getRoles().stream()
                    .anyMatch(role -> "ADMIN".equals(role.getCode()));
            data.put("isAdmin", isAdmin);
            data.put("role", isAdmin ? "admin" : "user");
            return Ret.success(data);
        }
        return Ret.error("用户名或密码错误");
    }

    /**
     * 用户退出
     */
    @PostMapping("/logout")
    public Ret<?> logout() {
        userService.logout();
        return Ret.success();
    }

    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/info")
    public Ret<?> getCurrentUser(@RequestHeader("Authorization") String token) {
        User user = userService.getCurrentUser();
        if (user != null) {
            Map<String, Object> data = new HashMap<>();
            data.put("user", user);
            // 检查是否是管理员
            boolean isAdmin = user.getRoles() != null && user.getRoles().stream()
                    .anyMatch(role -> "ADMIN".equals(role.getCode()));
            data.put("isAdmin", isAdmin);
            data.put("role", isAdmin ? "admin" : "user");
            return Ret.success(data);
        }
        return Ret.error("未登录");
    }

    @GetMapping("/current")
    public Ret<?> getCurrentUserFromSession() {
        User user = userService.getCurrentUser();
        if (user != null) {
            return Ret.success(user);
        }
        return Ret.error("未登录");
    }
} 